<template>
  <!-- 表单 -->
  <el-dialog :title="TagData.id?'编辑学科':'添加学科'" :visible="showDialog" @close="close" width="400px">
    <el-form ref="tags" :model="formData" :rules="rules" label-width="80px">
      <!-- id不存在的时候,才可以让选择学科显示 -->
      <el-form-item label="所属学科" prop="subjectID" v-if="!$route.query.value">
        <el-select placeholder="请选择学科" style="width: 100%" v-model="formData.subjectID">
          <el-option v-for="item in list" :key="item.value" :value="item.value" :label="item.label"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="标签名称" prop="tagName">
        <el-input v-model="formData.tagName" style="width:100%" placeholder="请输入标签名称" />
      </el-form-item>
    </el-form>
    <!-- footer插槽 -->
    <template v-slot:footer>
      <el-button @click="$emit('update:showDialog')">取消</el-button>
      <el-button type="primary" @click="addTag">确定</el-button>
    </template>
  </el-dialog>
</template>

<script>
import { simple } from '@/api/hmmm/subjects.js'
import { add, update } from '@/api/hmmm/tags'
export default {
  data () {
    return {
      // 学科列表
      list: [],
      formData: {
        subjectID: '',
        tagName: ''
      },
      rules: {
        tagName: [
          { required: true, message: '请输入标签名称', trigger: ['blur', 'change'] }
        ]
      }
    }
  },
  props: {
    showDialog: {
      type: Boolean,
      default: false
    },
    TagData: null
  },
  created () {
    this.getList()
  },
  methods: {
    close () {
      this.$emit('update:showDialog')
    },

    // 获取学科名称
    async getList () {
      const { data } = await simple()
      this.list = data
      console.log(this.list)
    },
    openDialog () {
      // 有数据就是修改
      if (this.TagData) {
        this.formData.subjectID = this.TagData.subjectID
        this.formData.tagName = this.TagData.tagName
      }
      // 清除表单校验
      this.$nextTick(() => {
        this.$refs.tags.clearValidate()
      })
    },
    // 确认添加标签
    addTag () {
      this.$refs.tags.validate(async flag => {
        if (!flag) return
        if (this.$route.query.id) this.formData.subjectID = this.$route.query.id
        if (this.TagData.id) {
          await update({ id: this.TagData.id, ...this.formData })
          this.$message.success('修改成功!')
        } else {
          // 没有id
          await add(this.formData)
          this.$message.success('添加成功!')
          console.log(this.TagData)
        }
        // 通知到父组件更新数据=> 获取父组件实例this.$parent
        // 关闭弹窗 刷新页面
        this.$parent.loadList()
        this.$emit('update:showDialog')
      })
    }
  }
}
</script>

<style scoped lang='less'></style>
